package cn.mall.framework.wxsdk.core.msg;

import lombok.Data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 微信公众号信息
 */
@Data
public class WeixinAccount {

	public WeixinAccount() {

	}

	public WeixinAccount(String appId, String appSecret, String aesKey, String token) {
		this.appId = appId;
		this.appSecret = appSecret;
		this.aesKey = aesKey;
		this.token = token;
	}

	/** 公众号原始ID */
	private String mpId;
	/** 公众号昵称 */
	private String nickName;
	/** 应用Id */
	private String appId;
	/** 应用密钥 */
	private String appSecret;
	/** 令牌 */
	private String token;
	/**  AES安全加密密钥 */
	private String aesKey;

	private boolean encrypt;
	/** 公众号类型 D:订阅号 E:企业号 S:服务号 */
	private String mpType;
	/** 是否认证 */
	private boolean pass;
	/** 应用凭证 */
	private String accessToken;
	/** 凭证有效时间(秒) */
	private long expiresIn;
	/** 预授权码 */
	private String preAuthCode;
	/** 预授权码有效时间(秒) */
	private long preAuthExpiresIn;
	/** JSAPI凭证 */
	private String jsTicket;
	/** JSAPI凭证有效时间(秒) */
	private long jsExpiresIn;
	
	/** 解析微信服务器返回消息生成高级API或服务的凭证  */
	public void createAccessToken(String result) {
		JSONObject tmp = JSON.parseObject(result);
		if (result.contains("access_token")) {
			setAccessToken(tmp.getString("access_token"));
		} else {
			setAccessToken(tmp.getString("component_access_token"));
		}
		long lose_time = (tmp.getLong("expires_in") - 60) * 1000
				+ System.currentTimeMillis();
		setExpiresIn(lose_time);
	}

	/** 解析微信服务器返回消息生成预授权码 */
	public void createPreAuthCode(String result) {
		JSONObject tmp = JSONObject.parseObject(result);
		setPreAuthCode(tmp.getString("pre_auth_code"));
		long lose_time = (tmp.getLong("expires_in") - 60) * 1000
				+ System.currentTimeMillis();
		setPreAuthExpiresIn(lose_time);
	}

	/** 解析微信服务器返回消息生成JSTICKET */
	public void createJsTicket(String result) {
		JSONObject tmp = JSONObject.parseObject(result);
		setJsTicket(tmp.getString("ticket"));
		long lose_time = (tmp.getLong("expires_in") - 60) * 1000
				+ System.currentTimeMillis();
		setJsExpiresIn(lose_time);
	}

	@Override
	public String toString() {
		return "MPAct{" + "mpId='" + mpId + '\'' + ", nickName='" + nickName
				+ '\'' + ", appId='" + appId + '\'' + ", appSecert='"
				+ appSecret + '\'' + ", token='" + token + '\'' + ", AESKey='"
				+ aesKey + '\'' + ", mpType='" + mpType + '\'' + ", pass="
				+ pass + ", accessToken='" + accessToken + '\''
				+ ", expiresIn=" + expiresIn + ", preAuthCode='" + preAuthCode
				+ '\'' + ", preAuthExpiresIn=" + preAuthExpiresIn
				+ ", jsTicket='" + jsTicket + '\'' + ", jsExpiresIn="
				+ jsExpiresIn + '}';
	}
}
